package com.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dao.CartDao;
import com.dao.ProductDao;
import com.dao.SysUserDao;
import com.pojo.Cart;
import com.pojo.SysUser;
import com.service.CartService;
import com.vo.CartVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;

/**
 * @author lifeng
 * @create 2022-11-28 11:03
 */
@Service
public class CartServiceImpl extends ServiceImpl<CartDao,Cart> implements CartService {

    @Autowired
    private CartDao cartDao;

    @Autowired
    private SysUserDao sysUserDao;

    @Autowired
    private ProductDao productDao;

    @Override
    public List<Cart> selectCartByUid(String username) {

        //拿到用户id
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        SysUser sysUser = sysUserDao.selectOne(wrapper);

        List<Cart> list = cartDao.selectAllByOne(sysUser.getUsername());

        //根据商品id找到商品的价格
        for (Cart cart : list) {
            Integer pId = cart.getPId();

            Integer priceByPid = Integer.valueOf(productDao.findPriceByPid(pId));

            cart.setSubtotal(priceByPid * cart.getCount());
        }

        return list;

    }

    //加入购物车
    @Override
    public void addCart(CartVo cartVo) {
        cartDao.insertByCartVo(cartVo);
    }

    /**
     * 根据id批量更新
     * @param carts
     */
    @Override
    public void updateByCartIds(List<Cart> carts) {
        for (Cart cart : carts) {
            cart.setStatus(1);
        }
        saveOrUpdateBatch(carts,100);
    }

    /**
     * 重写根据Id批量更新
     * @param entityList
     * @param batchSize
     * @return
     */
    @Override
    public boolean saveOrUpdateBatch(Collection<Cart> entityList, int batchSize) {
        return super.saveOrUpdateBatch(entityList, batchSize);
    }
}
